package com.shuai.robot.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.constant.UserConstant;
import com.shuai.common.constant.UserLevelLimitEnum;
import com.shuai.common.exception.BusinessException;
import com.shuai.robot.dto.ChatModelReq;
import com.shuai.robot.dto.UserDTO;
import com.shuai.robot.service.StreamChatService;
import com.shuai.robot.sse.OpenAISessionChatSSEListener;
import com.shuai.robot.xunfei.XunfeiRobotApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Collections;

@Service
public class StreamChatServiceImpl implements StreamChatService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${xs-robot.api-key}")
    private String apiKey;
    @Value("${xs-robot.api-secret}")
    private String apiSecret;
    @Value("${xs-robot.version}")
    private String version;


    @Override
    public void streamChat(long sessionId, String userId, String question, SseEmitter sseEmitter) {
        // 如果用户上传了api-key和api-secret，则按照用户的ak和sk请求，否则使用系统配置
        String userJson = stringRedisTemplate.opsForValue().get(UserConstant.USER_ATTRIBUTE_REDIS_KEY + userId);
        if (CharSequenceUtil.isBlank(userJson)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "身份信息过期,请重新登录!");
        }
        UserDTO userDTO = JSONUtil.toBean(userJson, UserDTO.class);
        String selectedApiKey = CharSequenceUtil.isBlank(userDTO.getApiKey()) ? apiKey : userDTO.getApiKey();
        String selectedApiSecret = CharSequenceUtil.isBlank(userDTO.getApiSecret()) ? apiSecret : userDTO.getApiSecret();

        UserLevelLimitEnum userLevelLimitEnum = UserLevelLimitEnum.fromLevelCode(userDTO.getLevel());

        ChatModelReq chatModelReq = ChatModelReq.builder()
                .stream(Boolean.TRUE)
                .model(version)
                .max_tokens(userLevelLimitEnum.getLimitCount())
                .messages(Collections.singletonList(ChatModelReq.
                        Message.
                        builder()
                        .role("user")
                        .content(question)
                        .build()))
                .build();
        XunfeiRobotApi.streamSessionReq(chatModelReq, selectedApiKey, selectedApiSecret,
                new OpenAISessionChatSSEListener(sseEmitter, question, sessionId, userId));
    }
}
